import { Component,<% if (!fieldsContainBlob) { %> Vue,<% } %> Inject } from 'vue-property-decorator';
<% if (fieldsContainBlob) { %>
  import { mixins } from 'vue-class-component';
  import JhiDataUtils from '@/shared/data/data-utils.service';
<% } %>
<%_
  let fieldsContainedValidators = [];
  for (idx in fields) {
    if (fields[idx].fieldValidate === true) {
      if (!fieldsContainedValidators.includes('numeric') && ['Integer', 'Long', 'Float', 'Double', 'BigDecimal'].includes(fields[idx].fieldType)) {
        fieldsContainedValidators.push('numeric');
      }
      if (!fieldsContainedValidators.includes('required') && fields[idx].fieldValidateRules.includes('required')) {
        fieldsContainedValidators.push('required');
      }
      if (!fieldsContainedValidators.includes('minLength') && fields[idx].fieldValidateRules.includes('minlength')) {
        fieldsContainedValidators.push('minLength');
      }
      if (!fieldsContainedValidators.includes('maxLength') && fields[idx].fieldValidateRules.includes('maxlength')) {
        fieldsContainedValidators.push('maxLength');
      }
      if (!fieldsContainedValidators.includes('minValue') && fields[idx].fieldValidateRules.includes('min')) {
        fieldsContainedValidators.push('minValue');
      }
      if (!fieldsContainedValidators.includes('maxValue') && fields[idx].fieldValidateRules.includes('max')) {
        fieldsContainedValidators.push('maxValue');
      }
    }
  }
  for (idx in relationships) {
    if (relationships[idx].relationshipValidate === true) {
      if (!fieldsContainedValidators.includes('required')) {
        fieldsContainedValidators.push('required');
      }
    }
  }
  if (fieldsContainedValidators.length !== 0) {
    let validators = fieldsContainedValidators.toString();
  _%>import {<%= validators %>} from 'vuelidate/lib/validators';
<%_ } _%>
<%_
    let dateFnsIncluded = false;
    for (idx in fields) {
        const fieldName = fields[ idx ].fieldName;
        const fieldType = fields[idx].fieldType;
        if ([ 'Instant', 'ZonedDateTime' ].includes(fieldType) && !dateFnsIncluded) {
            dateFnsIncluded = true;
_%>
import format from 'date-fns/format';
import isValid from 'date-fns/isValid';
import parse from 'date-fns/parse';
import parseISO from 'date-fns/parseISO';
import { DATE_TIME_LONG_FORMAT } from '@/shared/date/filters';
    <%_ } } _%>

<%_
    const importEntitiesSeen = [entityAngularName];
    let hasManyToMany = false;
    for (idx in relationships) {
      if (!relationships[idx].otherEntityIsEmbedded) {
        const otherEntityAngularName = relationships[idx].otherEntityAngularName;
        const otherEntityFileName = relationships[idx].otherEntityFileName;
        const otherEntityFolderName = relationships[idx].otherEntityFileName;
        const otherEntityClientRootFolder = relationships[idx].otherEntityClientRootFolder;
        const otherEntityModelName = relationships[idx].otherEntityModelName;
        if (relationships[idx].relationshipType === 'many-to-many' && relationships[idx].ownerSide === true) {
          hasManyToMany = true;
        }
        if (!importEntitiesSeen.includes(otherEntityAngularName)) {
_%>
  <% if (otherEntityAngularName === 'User' && authenticationType !== 'oauth2') { %>
import UserService from '@/admin/user-management/user-management.service';
  <% } else if (otherEntityAngularName !== 'User') { %>
import <%= otherEntityAngularName %>Service from '@/entities/<%= otherEntityClientRootFolder %><%= otherEntityFolderName %>/<%= otherEntityFileName %>.service';
import { I<%= otherEntityAngularName %> } from '@/shared/model/<%= otherEntityModelName %>.model';
  <% } } %>
<%_ importEntitiesSeen.push(otherEntityAngularName); } } _%>
import { I<%= entityAngularName %>, <%= entityAngularName %> } from '@/shared/model/<%= entityModelFileName %>.model';
import <%= entityAngularName %>Service from './<%= entityFileName %>.service';

const validations: any = {
  <%= entityInstance %>: {
    <%_ for (idx in fields) {
      const fieldName = fields[idx].fieldName;
      const fieldType = fields[idx].fieldType;
    _%>
    <%= fieldName %>:  {
    <%_ if (fields[idx].fieldValidate === true) { _%>
    <%_ if (fields[idx].fieldValidateRules.includes('required')) { _%>
    required,
    <%_ } _%>
    <%_ if (fields[idx].fieldValidateRules.includes('minlength')) { _%>
      minLength: minLength(<%= fields[idx].fieldValidateRulesMinlength %>),
    <%_ } _%>
    <%_ if (fields[idx].fieldValidateRules.includes('maxlength')) { _%>
      maxLength: maxLength(<%= fields[idx].fieldValidateRulesMaxlength %>),
    <%_ } _%>
    <%_ if (['Integer', 'Long', 'Float', 'Double', 'BigDecimal'].includes(fieldType)) { _%>
    numeric,
    <%_ if (fields[idx].fieldValidateRules.includes('min')) { _%>
      min: minValue(<%= fields[idx].fieldValidateRulesMin %>),
    <%_ } _%>
    <%_ if (fields[idx].fieldValidateRules.includes('max')) { _%>
      max: maxValue(<%= fields[idx].fieldValidateRulesMax %>),
    <%_ } _%>
    <%_ } _%>

    <%_ } _%>
    },
    <%_ } _%>
    <%_
    for (idx in relationships) {
      if (relationships[idx].relationshipValidate === true) { _%>
    <%= relationships[idx].relationshipFieldName %><%_ if (dto !== 'no') { _%>Id<%_ } _%>: {
      required
    },
    <%_ } _%>
  <%_ } _%>
  }
};

@Component({
  validations
})
export default class <%= entityAngularName %>Update extends <% if (fieldsContainBlob) { %>mixins(JhiDataUtils)<% } else { %>Vue<% } %> {
  @Inject('<%= entityInstance %>Service') private <%= entityInstance %>Service: () => <%= entityAngularName %>Service;
  public <%= entityInstance %>: I<%= entityAngularName %> = new <%= entityAngularName %>();
  <%_
    const entitiesSeen = [entityAngularName];
    for (idx in relationships) {
      if (!relationships[idx].otherEntityIsEmbedded) {
        const otherEntityName = relationships[idx].otherEntityName;
        const otherEntityNamePlural = relationships[idx].otherEntityNamePlural;
        const otherEntityAngularName = relationships[idx].otherEntityAngularName;
        if (!(otherEntityAngularName === 'User' && authenticationType === "oauth2")) {
  _%>
  <%_ if (!entitiesSeen.includes(otherEntityAngularName)) { %>
  @Inject('<%= otherEntityName %>Service') private <%= otherEntityName %>Service: () => <%= otherEntityAngularName %>Service;
  <%_ } _%>
  <%_ if (!entitiesSeen.includes(otherEntityNamePlural)) { %>
  public <%= otherEntityNamePlural %> : <% if (otherEntityAngularName === 'User') { %>Array<any><%_ } else { _%>I<%= otherEntityAngularName %>[]<%_ } _%> = [];
  <%_ } _%>
  <%_ entitiesSeen.push(otherEntityAngularName);entitiesSeen.push(otherEntityNamePlural); } } } _%>
  public isSaving = false;
  public currentLanguage = '';

  beforeRouteEnter(to, from, next) {
    next(vm => {
      if (to.params.<%= entityInstance %>Id) {
        vm.retrieve<%= entityAngularName %>(to.params.<%= entityInstance %>Id);
      }
      <%_ if (relationships.length > 0) { _%>
      vm.initRelationships();
      <%_ } _%>
    });
  }

  created(): void {
    this.currentLanguage = this.$store.getters.currentLanguage;
    this.$store.watch(
      () => this.$store.getters.currentLanguage,
      () => {
        this.currentLanguage = this.$store.getters.currentLanguage;
      }
    );
    <%_ if (hasManyToMany) { _%>
    <%_
      for (idx in relationships) {
      const otherEntityNamePlural = relationships[idx].otherEntityNamePlural;
      if (relationships[idx].relationshipType === 'many-to-many' && relationships[idx].ownerSide === true) {
      const relationshipFieldNamePlural = relationships[idx].relationshipFieldNamePlural;
    _%>
    this.<%= entityInstance %>.<%= relationshipFieldNamePlural %> = [];
    <%_ } } _%>
    <%_ } _%>
  }

  public save() : void {
    this.isSaving = true;
    <%_ for (idx in fields) {
        const fieldName = fields[ idx ].fieldName;
        const fieldType = fields[idx].fieldType;
    } _%>
    if (this.<%= entityInstance %>.id) {
      this.<%= entityInstance %>Service().update(this.<%= entityInstance %>).then((param) => {
        this.isSaving = false;
        this.$router.go(-1);
        <%_ if (enableTranslation) { _%>
        const message = this.$t('<%= i18nKeyPrefix %>.updated', { 'param' : param.id });
        <%_ } else {_%>
        const message = 'A <%= entityAngularName %> is updated with identifier ' + param.id;
        <%_ } _%>
        return this.$root.$bvToast.toast(message.toString(), {
          toaster: 'b-toaster-top-center',
          title: 'Info',
          variant: 'info',
          solid: true,
          autoHideDelay: 5000,
        });
      });
    } else {
      this.<%= entityInstance %>Service().create(this.<%= entityInstance %>).then((param) => {
        this.isSaving = false;
        this.$router.go(-1);
        <%_ if (enableTranslation) { _%>
        const message = this.$t('<%= i18nKeyPrefix %>.created', { 'param' : param.id });
        <%_ } else {_%>
        const message = 'A <%= entityAngularName %> is created with identifier ' + param.id;
        <%_ } _%>
        this.$root.$bvToast.toast(message.toString(), {
          toaster: 'b-toaster-top-center',
          title: 'Success',
          variant: 'success',
          solid: true,
          autoHideDelay: 5000,
        });
      });
    }
  }

  <%_
    let dateFunctionIncluded = false;
    for (idx in fields) {
        const fieldName = fields[ idx ].fieldName;
        const fieldType = fields[idx].fieldType;
        if ([ 'Instant', 'ZonedDateTime' ].includes(fieldType) && !dateFunctionIncluded) {
            dateFunctionIncluded = true;
  _%>
    public convertDateTimeFromServer(date: Date): string {
      if (date && isValid(date)) {
        return format(date, DATE_TIME_LONG_FORMAT);
      }
      return null;
    }

    public updateInstantField(field, event) {
      if (event.target.value) {
        this.<%= entityInstance %>[field] = parse(event.target.value, DATE_TIME_LONG_FORMAT, new Date());
      } else {
        this.<%= entityInstance %>[field] = null;
      }
    }

    public updateZonedDateTimeField(field, event) {
      if (event.target.value) {
        this.<%= entityInstance %>[field] = parse(event.target.value, DATE_TIME_LONG_FORMAT, new Date())
      } else {
        this.<%= entityInstance %>[field] = null;
      }
    }
    <%_ } } _%>

  public retrieve<%= entityAngularName %>(<%= entityInstance %>Id) : void {
    this.<%= entityInstance %>Service().find(<%= entityInstance %>Id).then((res) => {
<%_
        for (idx in fields) {
            const fieldName = fields[idx].fieldName;
            const fieldType = fields[idx].fieldType;
            if ([ 'Instant', 'ZonedDateTime' ].includes(fieldType)) {
_%>
      res.<%= fieldName %> = new Date(res.<%= fieldName %>);
<%_ } } _%>
      this.<%= entityInstance %> = res;
    });
  }

  public previousState() : void {
    this.$router.go(-1);
  }

  <%_ if (fieldsContainBlob && fieldsContainImageBlob) { _%>
  public clearInputImage(field, fieldContentType, idInput) : void {
    if (this.<%= entityInstance %> && field && fieldContentType) {
      if (this.<%= entityInstance %>.hasOwnProperty(field)) {
        this.<%= entityInstance %>[field] = null;
      }
      if (this.<%= entityInstance %>.hasOwnProperty(fieldContentType)) {
        this.<%= entityInstance %>[fieldContentType] = null;
      }
      if (idInput) {
        (<any>this).$refs[idInput] = null;
      }
    }
  }

  <%_ } _%>
  public initRelationships() : void {
    <%_
        let entitiesSet = new Set();
        for (idx in relationships) {
          if (!relationships[idx].otherEntityIsEmbedded) {
          const otherEntityName = relationships[idx].otherEntityName;
          const otherEntityNamePlural = relationships[idx].otherEntityNamePlural;
          const otherEntityAngularName = relationships[idx].otherEntityAngularName;
          if (!(otherEntityAngularName === 'User' && authenticationType === "oauth2") && !entitiesSet.has(otherEntityName)) {
            entitiesSet.add(otherEntityName);
    _%>
    this.<%= otherEntityName %>Service().retrieve().then((res) => {
      this.<%= otherEntityNamePlural %> = res.data;
    });
    <%_ } } } _%>
  }

  <%_ if (hasManyToMany) { _%>
  public getSelected(selectedVals, option) : any {
    if (selectedVals) {
      for (let i = 0; i < selectedVals.length; i++) {
        if (option.id === selectedVals[i].id) {
          return selectedVals[i];
        }
      }
    }
    return option;
  }
  <%_ } _%>
}
